package com.parking.bang.rpc.core.client;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.parking.bang.rpc.model.ReqMessage;
import com.parking.bang.rpc.model.RespMessage;

/**
 * after sent,call back
 * 
 * @author ivan
 *
 */
public class MessageSendCallback {
	private ReqMessage request;
	private RespMessage response;
	private Lock lock = new ReentrantLock();
	private Condition finish = lock.newCondition();

	public MessageSendCallback(ReqMessage request) {
		this.request = request;
	}

	public Object start() throws InterruptedException {
		try {
			lock.lock();
			finish.await(10 * 1000, TimeUnit.MILLISECONDS);
			if (this.response != null) {
				return this.response.getResult();
			} else {
				return null;
			}
		} finally {
			lock.unlock();
		}
	}

	public void over(RespMessage reponse) {
		try {
			lock.lock();
			finish.signal();
			this.response = reponse;
		} finally {
			lock.unlock();
		}
	}
}
